var keywords=[];
var guideKeyWords=[];
var checkboxId=[];
var allObj={};
var allArray=[];
var checkboxObj=[];

$(function () {
    var params = sessionStorage.getItem('questionId');
    if (!isNull(params)) {
        $(".box-title").text("编辑问题");
    }else{
        $(".box-title").text("新增问题");
    }
    loadTable1()
});

function loadTable() {
    var answer = $("#answerDesc").val();
    var data = {"answer": answer,"voicetext": ''};
    var obj={}
    if(checkboxId.length>0){
        checkboxId.map(function(item){
            obj[item]=item
        })
    }
    table = $("#answerList").DataTable({
        ajax: {
            url: baseQuestionUrl + "list/answer",
            headers: {
                "authorization": 'Bearer ' + getCookie(cookieName)
            },
            type: "GET",
            contentType: "application/json",
            data: function (req) {
                req.limit = req.length;
                req.answer = data.answer;
                req.voicetext = data.voicetext
            },
            dataSrc: function (res) {
                res.recordsTotal = res.data.total;
                res.recordsFiltered = res.data.total;
                allArray=res.data.rows;
                if (checkboxId.length===allArray.length){
                    document.getElementById('checkboxAll').checked = true
                }else{
                    document.getElementById('checkboxAll').checked = false
                }
                return res.data.rows;
            },
            error: function (request, error) {
                if (request.status === 401) {
                    $(location).attr('href', 'login.html');
                } else {
                    swal("失败");
                }
            }
        },
        serverSide: true,
        // data: data,
        destroy: true,
        bLengthChange: false,
        searching: false,
        ordering: false,
        select: false,
        columns: [
            {
                data: 'id',
                render:function(data, type, row){
                    // allObj[data]=row
                    if(obj[data]){
                        return '<input type="checkbox" class="checkbox" name="checkbox" id="' + data + '" onchange="selectReletion(' + data + ')" checked>'
                    }else{
                        return '<input type="checkbox" class="checkbox" name="checkbox" id="' + data + '" onchange="selectReletion(' + data + ')">'
                    }
                }
            },
            {data: 'answer'},
            {data: 'voicetext'},
            {
                data: 'created',
                render: function (data, type, row, meta) {
                    return formatDate1(row.created);
                }
            },
            {
                data: 'updated',
                render: function (data, type, row, meta) {
                    return formatDate1(row.updated);
                }
            }
        ],
        pagingType: "full_numbers",
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            },
            oAria: {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        }
    });
}

function loadTable1(){
    var url=baseQuestionUrl + 'select/answer';
    ajaxCommon.request('post',url,{},function(res){
        allArray=res.data
        res.data.map(function(item){
            allObj[item.id]=item
        })
        loadQuestion();
        loadAllKeyWord();
    })
}

function search(){
    $('#addQuestion').modal('show');
    loadTable();
}

function selectAll(obj){
    var eleBox=document.getElementsByClassName('checkbox');
    for (var i=0;i<eleBox.length;i++){
        eleBox[i].checked=obj.checked
    }
    if(obj.checked){
        var arr=[]
        allArray.map(item=>{
            arr.push(item.id)
        })
        checkboxId=arr
        checkboxObj=allArray
    }else{
        checkboxId=[]
        checkboxObj=[]
    }
}
function selectReletion(id){
    var obj=$('input.checkbox');
    for (var i=0;i<obj.length;i++){
        if(obj[i].id==id) {
            if (obj[i].checked) {
                checkboxId.push(obj[i].id);
                checkboxObj.push(allObj[obj[i].id])
            } else {
                var indexs = checkboxId.indexOf(obj[i].id)
                checkboxId.splice(indexs, 1);
                checkboxObj.splice(indexs, 1);
            }
        }
    }
    if (checkboxId.length===allArray.length){
        document.getElementById('checkboxAll').checked = true
    }else{
        document.getElementById('checkboxAll').checked = false
    }
}

function submitDesc(){
    $('#addQuestion').modal('hide');
    var str=''
    checkboxObj.map(function (item) {
        if(item) {
            str += '<li>' +
                '<img src="src/img/deleteRed.png" alt="刪除" onclick="deletePar(' + item.id + ')">' +
                '<p>' + item.answer + '</p>' +
                '</li>'
        }
    });
    $('#answerReletion').html(str)
}

function deletePar(item){
    var index=checkboxId.indexOf(item.toString());
    checkboxId.splice(index,1);
    checkboxObj.splice(index,1);
    submitDesc();
    console.log(checkboxId,checkboxObj)
}

function loadAllKeyWord() {
    var url = baseQuestionUrl + "list/keyWords?type=2&limit=1000";
    ajaxCommon.request('get',url,{},function (data) {
        loadKeyWord(data.data.rows);
    });
}

function loadKeyWord(allKeyWord) {
    var array = [];
    var idArray = [];
    allKeyWord.map(function (o1, i) {
        keywords.map(function (o2, j) {
            if (o2 === o1.keyword) {
                idArray.push(o1.id);
            }
        });
    });
    allKeyWord.map(function (obj) {
        var keyWord = {"id": obj.id, "text": obj.keyword};
        array.push(keyWord);
    });
    var keyWordSelect = $("#keyWord");
    keyWordSelect.select2({
        data: array
    });
    var marketingStr = '';
    var optionTemplate = '<option value="@value">@text</option>';
    array.map(function (obj) {
        marketingStr += optionTemplate.replace('@value', obj.id).replace('@text', obj.text);
    });
    keyWordSelect.empty().append(marketingStr).val(idArray).trigger("change");
    loadMoreKeyWord(allKeyWord);
}

function loadMoreKeyWord(allKeyWord) {
    var array = [];
    var idArray = [];
    allKeyWord.map(function (obj) {
        var moreKeyWord = {"id": obj.id, "text": obj.keyword};
        array.push(moreKeyWord);
    });
    var moreKeyWordSelect = $("#moreKeyWord");
    moreKeyWordSelect.select2({
        data: array
    });
    var optionTemplate = '<option value="@value">@text</option>';
    var marketingStr = '';
    array.map(function (obj) {
        marketingStr += optionTemplate.replace('@value', obj.id).replace('@text', obj.text);
    });
    if (!isNull(guideKeyWords)) {
        guideKeyWords.map(function (obj,i) {
            for (var j = 0; j < array.length; j++) {
                if (array[j].text === guideKeyWords[i]) {
                    idArray.push(array[j].id);
                }
            }
        });
        moreKeyWordSelect.empty().append(marketingStr).val(idArray).trigger("change");
    }
}

function loadQuestion() {
    var params = sessionStorage.getItem('questionId');
    if (!isNull(params)) {
        var url = baseQuestionUrl + "find/" + params;
        ajaxCommon.request('get',url,{}, function (data) {
            var question=data.data.question;
            var answer=data.data.answers;
            if (!isNull(question.keyWords)) {
                if(question.keyWords.split('、').length>0) {
                    keywords = question.keyWords.split('、');
                }else{
                    keywords = [question.keyWords]
                }
            }
            if (!isNull(question.guideKeyWords)) {
                if(question.guideKeyWords.split('、').length>0) {
                    guideKeyWords = question.guideKeyWords.split('、');
                }else{
                    guideKeyWords = [question.guideKeyWords]
                }

            }
            $("#id").val(question.id);
            $("#question").val(question.question);
            answer.map(function(item){
                checkboxId.push(item);
                checkboxObj.push(allObj[item])
            });
            loadAllKeyWord();
            submitDesc()
        });
    } else {
        loadAllKeyWord();
    }
}


function submit() {
    if (isNull($("#question").val())) {
        swal("问题不能为空");
        return;
    }
    if ($("#keyWord").select2("data").length <= 0) {
        swal("请选择关键字");
        return;
    }
    submitQuestion($("#question").val());

}

/**
 * 提交对问题的修改
 * @param fileUrl
 */
function submitQuestion(questions) {
    if (questions.match(new RegExp("\s"))) {
        swal("问题格式不正确");
        return;
    }
    var url;
    var params = sessionStorage.getItem('questionId');
    if (isNull(params)) {
        url = baseQuestionUrl + "add";
        id = "";
    } else {
        url = baseQuestionUrl + "update";
        id = params;
    }
    var keyWordArr = [];
    var keyWord = $("#keyWord").select2("data");
    $(keyWord).each(function (index, obj) {
        var keyWord = obj.text;
        keyWordArr.push(keyWord);
    });
    var keyWords = strBuffAdd(keyWordArr, "、");
    var moreKeyWordArr = [];
    var moreKeyWord = $("#moreKeyWord").select2("data");
    $(moreKeyWord).each(function (index, obj) {
        var moreKeyWord = obj.text;
        moreKeyWordArr.push(moreKeyWord);
    });
    var guideKeyWords = strBuffAdd(moreKeyWordArr, "、");
    var question = {
            id: id,
            keyWords: keyWords,
            guideKeyWords: guideKeyWords,
            question: questions
        };
    var data = JSON.stringify(question);
    console.log(data);
    ajaxCommon.request('post',url,data,function (data) {
        console.log(data)
        if (data.code===200){
            var answer={
                answer:'',
                keyword: ''
            };
            checkboxId.map(function(it){
                answer.answer+=it+','
            });
            answer.answer= answer.answer.substr(0,answer.answer.length-1)
            answer.keyword=data.data.id;
            var url1=baseQuestionUrl+'add/answerandquestion'
            ajaxCommon.request('post',url1,JSON.stringify(answer),function (data1) {
                if(data1.code===200){
                    swal('请求成功');
                    initPage('question_list','question/question_list.html')
                }
            })
        }else{

        }
    })
}
